<?php
namespace control;
/*
*食堂管理类
*/

class diningHallClass extends adIndexClass
{
    public const page = 'diningHall';
    private const table = 'dining_hall';
    private const tableMx = 'dining_hall_detail';
    public const title = '食堂管理';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '食堂编号',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "食堂名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'mealType'  => [
                        'name'  => "餐别",
                        'width' => 300,
                    ],
                    'manager'         => [
                        'name'  => '管理员',
                        'width' => 200,
                    ],
                    'deviceNo'          => [
                        'name'  => '打卡机序列号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂编号" => text(array("name" => "orderNo")),
                    "食堂名称"     => text(array("name" => "name")),
                    "打卡机序列号"     => text(array("name" => "deviceNo")),
                ],
                [
                    "管理人"     => selectMultiple(["name" => "staffId", 'table' => "staff",'where'=>"workFlow = '已复核'", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "状态" => select(["name" => "state", 'option' => ['启用','停用']]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .=  "<span onclick=\"newIframe('" . self::title . "编辑','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }

        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//食堂编号
            "name" => $this->post('name'),//食堂名称
            "deviceNo" => $this->post('deviceNo'),//打卡机序列号
            "manager" => $this->post('staffId'),//管理人
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "mealType":
                        $mealType = find(array('table'=>self::tableMx,'single'=>"orderId = '$array[id]' group by orderId",'field'=>"group_concat(mealType) as type"))['type'];
                        $row[] = $mealType;
                        break;
                    case "manager":
                        $row[] = self::findStaff(explode(',',$array['manager']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        /*****规则设置*********/
        $tr[] = ['', '餐别', '报餐截止时间', '就餐时间'];
        $result = find(array(
            'field' => "id as mxId,mealType,endTime,if(mealStartTime is null,'',concat(mealStartTime,' ~ ',mealEndTime)) as mealTime",
            'table' => self::tableMx." where orderId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->ruleRow($array);
            }
        }else{
            $tr[] = $this->ruleRow(['mxId'=>self::getId(), 'list'=>1]);
        }
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "食堂编号：" => text(["name" => "orderNo", 'class' => 'text', "value" => $info['orderNo']]),
                    must . "食堂名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    must . "管理员：" => selectMultiple(["name" => "manager[]",'multiple'=>true, 'title' => '管理员', 'table' => "staff",'where'=>"state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['manager']]),
                    must . "打卡机序列号：" => text(["name" => "deviceNo", 'class' => 'text', "value" => $info['deviceNo']]),
                ],
                [
                    "适用人员：" => componentClass::staffSelector($info['selector']),
                ],
                [
                    "备注：" =>  textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => '规则设置',
            'html' => $this->listTable(array('tr' => $tr, 'end' => true)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);
        //返回
        return $this->tab($data).$this->editJs();
    }

    public function editJs(): string
    {
        return <<<eof
        <script>
         //添加一行
         function addRow(e){
             $.post(root+'control/adIndex.html?cla=diningHall&fun=addRow',{},function (res){
                $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
             },'json');
         }
        </script>
eof;

    }

    /**
     * Desc : 学习经历
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function ruleRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['mealType', 'endTime', 'mealTime'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'ruleRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            select(array('name' => 'mealType[]', 'option'=>explode('，',para('mealOption')), 'title' => '餐别', 'value' => $array['mealType'])),
            text(array('name' => 'endTime[]', 'laydate' => ['type'=>'time'],'title' => '报餐截止时间', 'value' => $array['endTime'])),
            text(array('name' => 'mealTime[]', 'laydate' => ['range' => '~','type'=>'time'], 'title' => '就餐时间', 'value' => $array['mealTime']))
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    public function addRow(): bool|string
    {
        $res = json_decode($this->ruleRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId');
        $mealTypeArr = $this->post('mealType');
        $endTimeArr = $this->post('endTime');
        $mealTimeArr = $this->post('mealTime');

        $field = [
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'orderNo' => $this->post('orderNo'),
            'deviceNo' => $this->post('deviceNo'),
            'name' => $this->post('name'),
            'manager' => $this->post('manager')?implode(',',$this->post('manager')):'',
            'text' => $this->post('text'),
        ];
        $annotation = [
            'orderNo' => '食堂编号',
            'name' => '食堂名称',
        ];
        $rules = [
            'orderNo' => 'required',
            'name' => 'required',
        ];
        $staff = componentClass::returnStaffId($field['selector']);
        $field['member'] = implode(',',$staff);
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $warn = $this->checkStaff($staff,$id);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,'where'=>"name = '$field[name]' and id !='$id'")) >0){
            $json['warn'] = "已存在此食堂名称";
        }elseif(static::total(array('table'=>self::table,'where'=>"orderNo = '$field[orderNo]' and id !='$id'")) >0){
            $json['warn'] = "已存在此食堂编号";
        }elseif(static::is_null_array($mxIdArr)){
            $json['warn'] = '请添加食堂规则';
        }elseif(static::is_null_array($mealTypeArr)){
            $json['warn'] = '请填写餐别';
        }elseif(!empty($warn)){
            $json['warn'] = '员工'.$warn.'已在其他食堂中';
        }else {
            $this->startTrans();
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'state'=>'启用',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            foreach ($mxIdArr as $k=>$mxId){
                $mealTime = explode(' ~ ',$mealTimeArr[$k]);
                $mxField = [
                    'mealType'=>$mealTypeArr[$k],
                    'endTime'=>$endTimeArr[$k],
                    'mealStartTime'=>$mealTime[0]??'',
                    'mealEndTime'=>$mealTime[1]??'',
                ];
                $mx = query(self::tableMx,"id = '$mxId'");
                if(empty(array_filter($mxField, 'strlen'))) {
                    if ($mx['id']) delete(array('table' => self::tableMx, 'where' => " id = '$mxId' "));
                    continue;
                }
                if (empty($mx['id'])){
                    $warn = static::insert(array(
                        'table'=>self::tableMx,
                        'field'=> array_merge($mxField, [
                            'id'=>$mxId,
                            'orderId'=>$id,
                        ])
                    ));
                }else{
                    $warn = static::update(array(
                        'table'=>self::tableMx,
                        'field'=>$mxField,
                        'where'=>"id = '$mxId'"
                    ));
                }
                if (!in_array($warn, ["新增成功", "更新成功"])){
                    $json['warn'] = $warn;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }else{
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 检查是否有员工在其他食堂规则里
     * @param $staff
     * @param $id
     * @return bool|string
     */
    public function checkStaff($staff,$id): bool|string
    {
        $name = '';
        foreach ($staff as $stid){
            if (static::total(array('table'=>self::table,"where"=>" and member like '%{$stid}%' and id !='{$id}'")) >0){
                $staff = query('staff',"stid = '$stid'");
                $name = $staff['name'];
                break;
            }
        }
        return $name;
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                switch ($info['state']) {
                    case '停用':
                        $firState = '启用';
                        $titleOne = '启用';
                        break;
                    default:
                        $firState = '停用';
                        $titleOne = '停用';
                        break;
                }
                //按钮
                $button[] = [
                    "name" => $titleOne,
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{type:'{$firState}',id:'{$info['id']}'})",
                ];

            }
            if ($this->power(self::page,'del')){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            $tr[] = ['餐别', '报餐截止日期', '就餐时间'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['mealType'],
                    $array['endTime'],
                    $array['mealStartTime']?($array['mealStartTime'].'至'.$array['mealEndTime']):'',
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "食堂编号" => $info['orderNo'],
                        "食堂名称" => $info['name'],
                        "管理员" => self::findStaff(explode(',',$info['manager'])),
                        "打卡机序列号" => $info['deviceNo'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                    array(
                        "适用人员" => componentClass::showSelector($info['selector']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '规则设置',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true)),
            ]);
            $data['html']   .= $this->tableShow(array(
                '系统信息' => array(
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "状态" => $info['state'],
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] !='停用'){
                    $warn = "删除失败：不是停用状态";
                }else{
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
